<template>
  <div v-if="show" class="modal-overlay">
    <div class="modal-content">
      <div class="modal-header">
        <h3>物品入库</h3>
        <button class="close-btn" @click="handleClose">×</button>
      </div>
      <div class="modal-body">
        <div class="item-info">
          <p><strong>物品名称：</strong>{{ item.name }}</p>
          <p><strong>当前库存：</strong>{{ item.stockNum }} {{ item.unit }}</p>
        </div>
        <div class="form-group">
          <label for="stockInAmount">入库数量</label>
          <input
            id="stockInAmount"
            v-model.number="stockInAmount"
            type="number"
            min="1"
            placeholder="请输入入库数量"
            :class="{ 'error': showError && !isValidAmount }"
          >
          <div class="error-message" v-if="showError && !isValidAmount">
            请输入有效的入库数量（大于0的整数）
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="cancel-btn" @click="handleClose">取消</button>
        <button 
          class="submit-btn" 
          @click="handleSubmit"
          :disabled="isSubmitting"
        >
          {{ isSubmitting ? '提交中...' : '确认入库' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { API_CONFIG } from '../../config/apiConfig';
import type { InventoryItem } from '../../types/inventory';
import { ToastService } from '../../utils/toastService';

// 定义props
const props = defineProps<{
  show: boolean;
  item: InventoryItem;
}>();

const emit = defineEmits<{
  (e: 'close'): void;
  (e: 'stock-in-success'): void;
}>();

// 表单数据
const stockInAmount = ref<number | null>(null);
const isSubmitting = ref(false);
const showError = ref(false);

// 验证入库数量是否有效
const isValidAmount = computed(() => {
  return stockInAmount.value !== null && stockInAmount.value > 0 && Number.isInteger(stockInAmount.value);
});

// 关闭模态框
const handleClose = () => {
  stockInAmount.value = null;
  showError.value = false;
  emit('close');
};

// 提交表单
const handleSubmit = async () => {
  // 显示验证错误
  showError.value = true;
  
  // 验证表单
  if (!isValidAmount.value) {
    return;
  }

  isSubmitting.value = true;
  try {
    // 准备请求数据
    const requestData = {
      type: props.item.type,
      casNo: props.item.casNo,
      name: props.item.name,
      purity: props.item.purity,
      brand: props.item.brand,
      catalogNumber: props.item.catalogNumber,
      //specs: props.item.specs,
      unit: props.item.unit,
      stockNum: String(stockInAmount.value),
      location: props.item.location,
      expirationDate: props.item.expirationDate ? new Date(props.item.expirationDate).toISOString().split('T')[0] : undefined,
      researchGroupId: Number(props.item.researchGroupId)
    };

    // 发送请求
    const response = await fetch(`${API_CONFIG.BASE_URL}/sku`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      credentials: 'include',
      body: JSON.stringify(requestData)
    });

    const result = await response.json();
    
    if (result.code === 0 || result.code === '0') {
      emit('stock-in-success');
      handleClose();
    } else {
      ToastService.error(`入库失败: ${result.msg}`);
    }
  } catch (error) {
    console.error('入库请求失败:', error);
    ToastService.error('入库失败，请检查网络连接');
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  color: #999;
  cursor: pointer;
  padding: 4px;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 24px;
}

.item-info {
  margin-bottom: 20px;
  padding: 12px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.item-info p {
  margin: 8px 0;
  font-size: 14px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-size: 14px;
}

.form-group input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.form-group input:focus {
  border-color: #40a9ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-group input.error {
  border-color: #ff4d4f;
}

.error-message {
  color: #ff4d4f;
  font-size: 12px;
  margin-top: 4px;
}

.modal-footer {
  padding: 16px 24px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.cancel-btn,
.submit-btn {
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background: white;
  border: 1px solid #d9d9d9;
  color: #666;
}

.cancel-btn:hover {
  color: #40a9ff;
  border-color: #40a9ff;
}

.submit-btn {
  background: #1890ff;
  border: none;
  color: white;
}

.submit-btn:hover {
  background: #40a9ff;
}

.submit-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}
</style>